<?php

require_once 'extend/alipay-sdk/AopClient.php';
require_once 'extend/alipay-sdk/request/AlipaySystemOauthTokenRequest.php';
require_once 'AlipayConfig.php';

class AlipayHelper{

    /**
     * @return AopClient
     */
    public static
    function get_aop_client(){
        $aop_client                     = new AopClient();
        $aop_client->appId              = ALIPAY_APPID;
        $aop_client->rsaPrivateKey      = ALIPAY_RSA_PRIVATE_KEY;
        $aop_client->alipayrsaPublicKey = ALIPAY_ALIPAYRSA_PUBLIC_KEY;
        $aop_client->signType           = ALIPAY_SIGN_TYPE;
        return $aop_client;
    }

    /**
     * @param string $auth_code
     * @return
     * {
     *      "error_response":{
     *      "code":"40002",
     *      "msg":"Invalid Arguments",
     *      "sub_code":"isv.code-invalid",
     *      "sub_msg":"授权码code无效"
     *      },
     *      "sign":"PV5gDaUtIgdImyCE0gJR+J9RL07JCocf6SotIdbJSw0m1xQPCyw5t13vef9Cgr8y+JfiN8+Hfr+EdupzKk34r5dca5ZYrWgMlLeMt3ECKIHWgEPiE7BRo/tEL4pEbcRwWUoPuVrwF4IVu5Cfg9Rk/k4wAwLfDJ5q8Psa748Ja7GXdRgSi9VNS+ptYWF5vuqsBYXbO38z/eqQvSXQ/IlDKzTDiEAY1Q38vqofrQqzs04DsnCOhvTT0jCQ/UykouC0qoAl5YEAD4K2U3uCegjsHjpxcAQOHLuA/WvV16L1MjA/y5M+y0qvh/hl+FQtDzkCPBx8AEZ3XdOu06JlCS7kBA=="
     * }
     *
     * {
     * "code":2000,
     * "msg":"",
     * "data":{
     *      "access_token":"authusrBc19837c1f22d49ffbab7e75f7924eX11",
     *      "expires_in":1296000,
     *      "re_expires_in":2592000,
     *      "refresh_token":"authusrBd9120579c87f449f970cc9b2d190bX11",
     *      "user_id":"2088902491788112"
     *       }
     * }
     *
     *
     */
    public static
    function get_auth_token(string $auth_code){
        $aop_client = self::get_aop_client();
        $request    = new AlipaySystemOauthTokenRequest();
        $request->setGrantType('authorization_code');
        $request->setCode($auth_code);
        try{
            $result = $aop_client->execute($request);
        }catch(Exception $e){
            return return_array(6000, '调用阿里接口异常', $e->getMessage());
        }
        return self::fmt_execute_ret($request->getApiMethodName(), $result);
    }

    public static
    function refresh_token(string $refresh_token){
        $aop_client = self::get_aop_client();
        $request    = new AlipaySystemOauthTokenRequest();
        $request->setGrantType('refresh_token');
        $request->setRefreshToken($refresh_token);
        try{
            $result = $aop_client->execute($request);
        }catch(Exception $e){
            return return_array(6000, '调用阿里接口异常', $e->getMessage());
        }
        return self::fmt_execute_ret($request->getApiMethodName(), $result);

    }

    /**
     * 获取会员授权信息
     * @param string $auth_token
     * @return
     *
     * @throws Exception
     */
    public static
    function get_user_info(string $auth_token){
        $aop_client = self::get_aop_client();
        $request    = new AlipayUserInfoShareRequest();
        $result     = $aop_client->execute($request, $auth_token);
        $result_arr = json_decode(json_encode($result), true);

        $response_node = str_replace(".", "_", $request->getApiMethodName())."_response";
        if(!$result_arr){
            trace('[error] 调用阿里接口异常:');
            trace($result);
            return return_array(6000, '调用阿里接口异常');
        }
        if(!empty($result_arr[$response_node])){
            return return_array(2000, '', $result_arr[$response_node]);
        }
        return return_array(4000, $result_arr['error_response']['sub_msg']);

    }

    /**
     * 格式化 返回格式
     * @param $method_name
     * @param SimpleXMLElement $result
     * @return array
     */
    private static
    function fmt_execute_ret($method_name, $result){
        $result_arr    = json_decode(json_encode($result), true);
        $response_node = str_replace(".", "_", $method_name)."_response";
        if(!$result_arr){
            trace('[error] 调用阿里接口异常:');
            trace($result);
            return return_array(6000, '调用阿里接口异常');
        }
        if(!empty($result_arr[$response_node])){
            return return_array(2000, '', $result_arr[$response_node]);
        }
        return return_array(4000, $result_arr['error_response']['sub_msg']);

    }


}